<?php
/**
 *
 *
 */
class Yz_Action_InsertItem
    extends Yz_Action_Insert
{

    /**
     *  @var array( fieldName: fieldSelectClause )
     */
    protected $fields = array();

    /**
     *  @var array( alias: tableClause )
     */
    protected $tables = array();

    /**
     *  @var Item
     */
    protected $values;


    /************************************
     *          Public methods          *
     ************************************/


    /**
     *  @param mixed $item
     *  @return this
     */
    public function setItem(Yz_Item_Interface $item)
    {
        $this->values = $item;
        // prevent returning results after changing parameters
        $this->count = null;
        return $this;
    }


    /**
     *  @return int
     */
    public function getInsertId()
    {
        if (null === $this->count)
            throw StateError::_new_();
        $id = $this->values->getId();
        if (! $id)
            $id = $this->statement->getInsertId();
        $this->count = null;
        return $id;
    }


    /************************************
     *        Protected methods         *
     ************************************/

    /** Verify any arguments before building query
     *  virtual method
     *  @return this
     */
    protected function verifyArguments()
    {
        debug();
        if (! $this->values) {
            // assert that if values are non-empty, the fields have been set, too (@see identifyValues)
            throw StateError::_new_();
        }
        return $this;
    }


    /**
     *  Apply the arguments to the SQL statement
     *      Setup limit to avoid occasional selection of all rows
     *  @param Yz_SQL_Statement $sql
     *  @return this
     */
    protected function applyArguments(Yz_SQL_Statement $sql)
    {
        debug();
        $values = $this->values->toArray();
        if (! isset($values['id']))
            $values['id'] = new Yz_SQL_Literal('DEFAULT');
        foreach ($this->references as $refField)
            if (isset($values[$refField])) {
                assert('$values[$refField] instanceof Yz_Item_Interface');
                $values[$refField] = $values[$refField]->getId();
            }
        $sql
            ->bindArray($values)
        ;
        return $this;
    }



}
